<template>
  <popup ref="select_popup" @on-back-click="emit('onCancel')">
    <view class="select_popup_box">
      <scroll-view
        scroll-y="true"
        class="scroll"
        :scroll-into-view="`selected-scroll${chooseIndex}`"
        :scroll-with-animation="true"
      >
        <view
          v-for="(item, index) in props.list"
          :key="index"
          class="item"
          :id="`selected-scroll${index}`"
          :class="{ choose: chooseIndex == index }"
          @click="onSelectedEvent(item, index)"
        >
          {{ item }}
        </view>
      </scroll-view>
    </view>
  </popup>
</template>

<!-- 底部弹窗 -->
<script lang="ts" setup>
import { ref, type PropType } from 'vue'
import popup from './popup.vue'

//接受父组件参数
const props = defineProps({
  //数据列表
  list: {
    type: Array as PropType<any[]>,
    default: [],
  },
})

//自定义事件
const emit = defineEmits<{
  /**
   * 点击选中事件
   */
  (e: 'onSelected', item: { data: any; index: number }): void
  /**
   * 取消事件
   */
  (e: 'onCancel'): void
}>()

//当前选中下标
const chooseIndex = ref(0)

//点击选中
const onSelectedEvent = (item: any, index: number) => {
  chooseIndex.value = index
  emit('onSelected', { data: item, index: index })
  close()
}

// 弹窗实例
const select_popup = ref<InstanceType<typeof popup> | null>(null)

//  打开
const open = () => {
  select_popup.value?.open()
  let index = chooseIndex.value
  chooseIndex.value = 0
  setTimeout(() => {
    chooseIndex.value = index
  }, 200)
}

// 关闭
const close = () => {
  select_popup.value?.close()
}

//对外暴露
defineExpose({
  open,
  close,
})
</script>

<style scoped lang="scss">
.select_popup_box {
  width: 100%;
  padding: 30rpx 0;
  .scroll {
    height: 300rpx;

    .item {
      text-align: center;
      width: 100%;
      height: 70rpx;
      line-height: 70rpx;
      color: rgb(100, 96, 96);
    }

    .choose {
      color: rgb(254, 145, 56);
    }
  }
}
</style>
